package com.itheima.ydd.controller;

import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.CommonImgDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 文件上传下载控制类
 */

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {


    @Value("${ydd.path}")
    private String basePath;

/**
 * 文件上传
 * @param file
 * @return
 */

    @PostMapping("/upload")
    public ResultData upload(@RequestBody MultipartFile file ,String type ){
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后的临时文件会删除
        log.info(file.toString());
        //原始文件名称
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名，防止文件名重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String savePath = "upload/"+type+"/"+ sdf.format(new Date());
        File newFile = new File(basePath);
        if (!newFile.exists()){
            newFile.mkdirs();
        }
        try{
            file.transferTo(new File(basePath+"\\"+fileName));
        }catch (IOException e){
            e.printStackTrace();
        }
        CommonImgDto commonImgDto = new CommonImgDto();
        commonImgDto.setSavePath(savePath+"/"+fileName);
        commonImgDto.setMime(type);
        commonImgDto.setName(fileName);
        commonImgDto.setSize((int)file.getSize());
        return ResultData.ok("",commonImgDto);
    }

}
